package com.example.demo.leetcode.classics150;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname _45快乐数
 * @description
 * @date 2023/07/22 9:28
 * <p>
 * ******************************************************
 */
public class _45快乐数 {

    public boolean isHappy(int n) {
        // 也可以用Set来解决判断是否之前遍历过
        // 想象成链表求环
        int slow = n;
        int fast = powAndSum(n);
        while (fast != 1 && slow != fast) {
            slow = powAndSum(slow);
            fast = powAndSum(powAndSum(fast));
        }
        return fast == 1;
    }

    private int powAndSum(int n) {
        int res = 0;
        int i = 0;
        long temp;
        while (n > 0) {
            // 123 % 10 = 3
            // 12 % 10 = 2
            // 123 % 10 = 1
            int d = n % 10;
            n = n / 10;
            res += d * d;
        }
        return res;
    }
}
